
<template>
  <transition
    name="imTreeUser"
    enter-active-class="animated slideInRight faster"
    leave-active-class="animated slideOutRight faster"
  >
    <div
      class="win-modal allModal"
    >
      <div
        class="main-content"
        style="top:0;"
      >
        <div
          id="scroll-wrapper"
          class="mui-scroll-wrapper"
          style="touch-action: none;"
        >
          <i
            v-show="showSelected"
            @tap="clearSelect"
            class="je-fixed-button je-audio-btn mui-icon mui-icon-trash clear"
          />
          <div class="mui-scroll">
            <div
              id="slider"
              @slide="slide"
              class="mui-slider"
              data-total="2"
            >
              <div class="mui-slider-group">
                <!--待选数据 -->
                <div
                  v-show="showWaitItem"
                  class="mui-slider-item"
                >
                  <p
                    v-if="!getTreeData || getTreeData.length === 0"
                    class="noDatas"
                  >
                    暂无待选数据
                  </p>
                  <!--:load="loadNode" lazy-->
                  <el-tree
                    ref="tree"
                    :data="getTreeData"
                    :props="props"
                    :filter-node-method="filterNode"

                    @check="handleCheckChange"
                    @node-click="handleNodeClick"
                    @node-expand="handleNodeExpand"
                    :render-content="renderContent"
                    :show-checkbox="isMultiple"
                    :default-expanded-keys="expandIds"
                    :check-strictly="cfg.selectType == 'N'"
                    :highlight-current="true"
                    node-key="id"
                  >
                    <span
                      slot-scope="{ node }"
                      class="custom-tree-node"
                    >
                      <span
                        v-if="node.data.photo"
                        v-html="node.data.photo"
                        class="headerImg"
                      />
                      <span class="userName">{{ node.label }}</span>

                    </span>
                  </el-tree>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
export default {
  name: 'TreeModal',
  props: {
    cfgcopy: {
      type: Object,
      default: () => {},
    },
    showChecked: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      cfg: '',
      type: '',
      selection: [],
      selectwinTreeInfo: { keyword: '' },
      activeId: '',
      isMultiple: false,
      checkboxAll: false,
      listsLength: 0,
      showWaitItem: true,
      showSelected: false,
      data: [],
      expandIds: [],
      checkIds: [],
      pathText: '',
      secondNode: [],
      thirdNode: [],
      props: {
        label: 'text',
        children: 'children',
        isLeaf: 'leaf',
      },
    };
  },
  computed: {
    getTreeData() {
      return this.data;
    },
  },
  created() {
    const oldBack = mui.back;
    mui.back = () => {
      oldBack();
    };
    this.cfg = this.cfgcopy;
    const cfgs = JE.value(this.cfg.configInfo, '').split(',');
    let _code = cfgs[0];// 配置编码
    if (JE.isEmpty(this.cfg.url) && JE.isEmpty(_code)) {
      JE.alert('编码不存在，请检查！');
      return;
    }
    this.isMultiple = ['M_', 'M'].indexOf(cfgs[3]) != -1; // 是否多选
    this.$nextTick(() => {
      mui.init({
        swipeBack: false, // 🈲用右滑关闭功能
      });
      if (this.isMultiple) {
        document.querySelector('#scroll-wrapper').style.top = `${0}px`;
        let item2Show = false; // 子选项卡是否显示标志
        document.querySelector('#slider').addEventListener('slide', (event) => {
          if (event.detail.slideNumber === 1 && !item2Show) {
            // 切换到第二个选项卡
            // 根据具体业务，动态获得第二个选项卡内容；
            // 改变标志位，下次直接显示
            item2Show = true;
          }
        });
      } else {
        document.querySelector('#scroll-wrapper').style.top = 0;
      }
    });
    this.async = ['M_', 'S_'].indexOf(cfgs[3]) != -1;// 是否异步

    // 人员选择器，默认换成人员字典
    this.type = this.cfg.type;
    if (this.cfg.type == 'user') {
      this.cfg.type = 'tree';
      cfgs[0] = _code = 'JE_CORE_DEPTUSER';
      cfgs[2] = (cfgs[2] || '').replaceAll('USERNAME', 'text').replaceAll('USERID', 'id').replaceAll('USERCODE', 'code');
      this.cfg.configInfo = cfgs.join(',');
    }

    // 辅助配置项
    if (JE.isNotEmpty(this.cfg.otherConfig)) {
      const otherConfig = JE.isString(this.cfg.otherConfig) ? JE.decode(this.cfg.otherConfig) : this.cfg.otherConfig;
      // 主键
      if (JE.isNotEmpty(otherConfig.pkName)) {
        this.cfg.pkName = otherConfig.pkName;
      }
    }
    this.initConfig();
    // 初始化
    const that = this;
    this.loadTree('ROOT', {
      callback() {
        that.initValue();
      },
    });
  },
  mounted() {
    window.addEventListener('creatGroupBackTree', (target) => {
      // 执行默认选中
      this.$nextTick(() => {
        const idArray = [];
        target.detail.selection.filter((dataItem) => {
          idArray.push(dataItem.id);
        });
        this.$set(this.cfgcopy, 'value', idArray.length > 1 ? idArray.join(',') : idArray[0]);
        this.initValue();
      });
    });
    this.$nextTick(() => {
      mui('.mui-input-row input').input();
      // 监听input框 清除按钮的点击事件
    });
    // 设置滚动条参数
    mui('#scroll-wrapper').scroll({
      bounce: false, // 回弹
      indicators: false, // 是否显示滚动条
      scrollY: true, // 是否竖向滚动
      scrollX: true, // 是否横向滚动
      deceleration: mui.os.ios ? 0.003 : 0.0009,
    });
  },
  methods: {
    // 初始化tree  配置
    initConfig() {
      // 初始化数据集
      const cfgs = JE.value(this.cfg.configInfo, '').split(',');
      const _code = cfgs[0];// 配置编码
      this.cfg.dataMap = {};
      this.cfg.pkName = JE.value(this.cfg.pkName || this.cfg.valueType, 'code');// 主键
      this.cfg.selectType = JE.value(cfgs[4], 'T');// N(上下都不级联) | T(选父节点级联选中子节点) | D(选子节点级联选择父节点) | A(上下全部级联)
      // 根节点过滤
      let rootId = '';// JE.toXT(JE.value(otherConfig.rootId,''),me.formatData,me.parentData);
      // url取值
      if (JE.isEmpty(rootId) && (_code.split('/').length > 1 || _code.split('\\').length > 1)) {
      // url
        rootId = '__url';
      }
      // 查询选择的树形默认异步操作
      const ddList = [{
        ddCode: _code,
        ddName: '',
        async: false, // this.async,
        whereSql: this.cfg.whereSql,
        orderSql: '',
        parentSql: '',
        rootId,
        nodeInfo: _code,
        params: this.cfg.params || {},
        initParams: {},
        moreRoot: false,
        queryField: '',
        nodeField: '',
        formatValue: '',
      }];

      // var url = '/dd/treeAction!loadTree.action',
      let url = JE.getUrlMaps('je.core.dd.tree.loadTree');
      let params = {
        node: 'ROOT',
        onlyItem: true,
        excludes: 'checked',
        strData: JE.encode(ddList),
      };

      if (this.cfg.type == 'user') {
      // url = 'rbac/userAction!loadAppUser.action';
        url = JE.getUrlMaps('je.core.rbac.user.loadAppUser');
        params = {
          whereSql: this.cfg.whereSql,
        };
      }
      const dicCfg = {};
      JE.each(ddList, (item) => {
        dicCfg[item.ddCode] = item;
      });
      // 树形配置信息
      this.cfg.treeConfig = {
        params: JE.apply(params, this.cfg.params || {}),
        url: this.cfg.url || url,
        dicCfg,
        dicCfgList: ddList,
      };
    },
    // 查询
    filterNode(value, data) {
      if (!value) return true;
      return data.text.indexOf(value) !== -1;
    },
    // 选中或取消选中
    handleCheckChange(data, checkobj) {
      this.selection = [];
      const { checkedNodes } = checkobj;
      const exp = this.cfg.enableExp; // 有效数据表达式
      checkedNodes.forEach((item) => {
        if (JE.isNotEmpty(exp)) {
          if (JE.value(JE.eval(JE.toXT(exp, item), `可选表达式错误：${exp}`), false)) {
            this.selection.push(item);
          }
        } else if (item.disable == '0') {
          this.selection.push(item);
        }
      });
      checkobj.checkedKeys.length > 0 && this.selection.length == 0 && (JE.msg('该部门暂无人员!'));
      this.$emit('selection', { boolean: this.showChecked, obj: this.selection });
    },
    // 异步节点展开  已经全选的处理
    handleNodeExpand(data, node) {
      const expandNodes = node.childNodes;
      if (expandNodes.length > 0) {
        expandNodes.forEach((item) => {
          if (JE.isNotEmpty(this.cfg.enableExp)) {
            if (item.checked && JE.value(JE.eval(JE.toXT(this.cfg.enableExp, item.data), `可选表达式错误：${this.cfg.enableExp}`), false)) {
              this.selection.push(item.data);
            }
          } else if (item.checked && item.data.disable == '0') {
            this.selection.push(item.data);
          }
        });
        // 去重
        this.selection = this.dedupe(this.selection);
      } else if (expandNodes.length === 0) {
        setTimeout(() => {
          const checkNodes = this.$refs.tree.getCheckedNodes(true);
          checkNodes.forEach((item) => {
            if (JE.isNotEmpty(this.cfg.enableExp)) {
              if (JE.value(JE.eval(JE.toXT(this.cfg.enableExp, item), `可选表达式错误：${this.cfg.enableExp}`), false)) {
                this.selection.push(item);
              }
            } else if (item.disable == '0') {
              this.selection.push(item);
            }
          });
          // 去重
          this.selection = this.dedupe(this.selection);
        }, 1500);
      }
    },
    // 数组去重
    dedupe(array) {
      return Array.from(new Set(array));
    },
    // 点击node 节点
    handleNodeClick(data, obj) {
      // if (!this.isMultiple) {
      //   if (JE.isNotEmpty(this.cfg.enableExp)) {
      //     if (JE.value(JE.eval(JE.toXT(this.cfg.enableExp, data), `可选表达式错误：${this.cfg.enableExp}`), false)) {
      //       this.selection = [];
      //       this.selection.push(data);
      //     }
      //   } else if (data.disable == '0') {
      //     this.selection = [];
      //     this.selection.push(data);
      //   }
      //   this.$emit('selection', { boolean: this.showChecked, obj: this.selection });
      // }
    },
    // 异步加载 tree
    loadNode(node, resolve) {
      console.log(node, node.level);
      if (node.level == 0) {
        return resolve(this.data);
      }
      // 最后一级  return
      if (node.isLeaf) return resolve([]);

      setTimeout(() => {
        this.loadTree(node.data.id_ || node.id, {
          callback(data) {
            resolve(data);
          },
        });
      }, 50);
    },
    // 滑动
    slide() {
      // const index = e.detail.slideNumber;
    },
    // 删除所有已选数据
    clearSelect() {
      this.selection = [];
      this.$refs.tree.setCheckedKeys([]);
    },
    // 删除某一个选中的数据
    deleteItem(index) {
      this.selection.splice(index, 1);
      this.$refs.tree.setCheckedNodes(this.selection);
    },
    // 初始化值
    initValue() {
      const that = this;
      let { value } = this.cfg;
      const { pkName } = this.cfg;
      const cfgs = (this.cfg.configInfo || '').split(',');
      const fs = JE.isNotEmpty(cfgs[1]) ? cfgs[1].split('~') : [];
      const rs = JE.isNotEmpty(cfgs[2]) ? cfgs[2].split('~') : [];
      if (fs.length != rs.length) { return; }
      let _pkName = '';// 表单对应的主键值字段名

      JE.each(rs, (name, index) => {
        if (name == pkName) {
          _pkName = fs[index];
          // 如果是表单，但是没有对应的主键字段，自动生成，用于下次初始化值用：一般用于查询界面
          // eslint-disable-next-line no-shadow
          const type = document.documentElement.getAttribute('data-type');
          if (['form', 'search'].indexOf(type) != -1 && window.APP && window.APP.form) {
            // 添加默认字段
            const field = window.APP.form.getFields(_pkName);
            if (!field) {
              const form = JE.select('.je-form');
              const dom = document.createElement('input');
              dom.setAttribute('type', 'hidden');
              dom.setAttribute('class', 'je-submit-field');
              dom.setAttribute('data-name', _pkName);
              form.appendChild(dom);
              window.APP.form._createField({
                name: _pkName,
                xtype: 'textfield',
                dom,
                options: {},
              });
            }
            value = window.APP.form.getValues(_pkName);
          }
          return false;
        }
      });
      // 如果值为空或者没有对应的主键字段，取消默认选中
      if (JE.isEmpty(value)) { return; }

      // 查询节点
      JE.ajax({
        // url:'/dd/treeAction!findAsyncNodes.action',
        url: JE.getUrlMaps('je.core.dd.tree.findAsyncNodes'),
        params: {
          type: pkName || 'id',
          value,
          strData: JE.encode(that.cfg.treeConfig.dicCfgList),
        },
        callback(success, obj) {
          if (success) {
            that.recursionObj(obj, false);
            // 已选择的数据
            that.selection = obj;
            // 默认展开的节点集合
            obj.forEach((item) => {
              that.expandIds.push(item.parent.split('_')[0]);
              that.checkIds.push(item.id);
            });
            that.expandIds = that.dedupe(that.expandIds);
            // 单选、多选的默认高亮
            if (!that.isMultiple) {
              // 单选
              that.$refs.tree.setCurrentKey(obj[0].id);
            } else {
              // 多选
              that.$nextTick(() => {
                that.$refs.tree.setCheckedKeys(that.checkIds);
              });
            }
          }
        },
      });
    },
    // 递归处理多选时候数据的禁用
    recursionObj(obj, ifcfg) {
      if (obj && typeof obj == 'object' && obj.constructor == Array) {
        obj.forEach((item, index) => {
          // 待选数据的总数计算
          if (ifcfg) {
            this.listsLength += 1;
          }
          // 记录下系统配置的disabled值  0 可选有效数据  1 不可选无效数据
          obj[index].disable = obj[index].disabled;
          // 默认全部能选
          obj[index].disabled = false;
          // id值转换
          obj[index].id_ = item.id;
          const keyId = item.id.split('_')[0];
          obj[index].id = keyId;
          // 在本地store根据id存储数据
          this.cfg.dataMap[item.id] = item;
          // 根据nodepath字段 处理已选数据 名字下面展示部门级联 **公司/**部门/张三
          const path = item.nodePath.substr(6).split('/');
          let pathText = '';
          path.forEach((id) => {
            // 要判断本地store中是否有保存的数据  不然会报错  影响后续程序的执行
            pathText += this.cfg.dataMap[id] ? `/${this.cfg.dataMap[id].text}` : '';
          });
          obj[index].pathText = pathText.substr(1);
          // 人员选择 添加头像
          if (this.type === 'user' && item.leaf) {
            this.$set(obj[index], 'photo', JE.getUserPhoto(item.bean.ID, true));
          }
          // 把bean字段中的数据放出来
          Object.assign(obj[index], item.bean);
          // children字段有数据 就递归处理
          if (item.children.length > 0) {
            this.recursionObj(item.children, ifcfg);
          }
        });
      }
    },

    // 加载数据
    loadTree(id, cfg) {
      const that = this;
      let { dataMap } = this.cfg;
      cfg = cfg || {};

      // 初始化数据
      if (JE.isEmpty(dataMap) && id === 'ROOT') {
        const dicInfo = this.cfg.treeConfig.dicCfgList[0];
        id = JE.isEmpty(dicInfo.nodeInfo) ? 'ROOT' : `ROOT_${dicInfo.nodeInfo}`;

        const root = {
          id, nodeInfo: dicInfo.nodeInfo, children: [], text: '全部',
        };
        this.cfg.dataMap = dataMap = {};
        this.cfg.dataMap[id] = root;
      }

      const node = dataMap[id];
      if (JE.isEmpty(node)) { return; }

      // 树形配置信息
      const treeCfg = this.cfg.treeConfig;

      // 加载数据
      const { params, url } = treeCfg;
      if (id.split('_')[0] != 'ROOT') {
        const nodeId = id.split('_')[0];
        // 修改rootid
        let strData = JE.decode(params.strData);
        JE.each(strData, (item) => {
          if (JE.isEmpty(item.nodeInfo) || item.nodeInfo == node.nodeInfo) {
            item.rootId = nodeId;
            item.isRoot = '0';
            strData = [item];
            return false;
          }
        });
        params.strData = JE.encode(strData);
      }
      console.log();
      JE.ajax({
        url,
        params,
        callback(success, obj) {
          // 递归处理数据
          if (success) {
            that.recursionObj(obj, true);

            // 异步 获取一级节点的数据  同步 就是全部的集合
            if (id === 'ROOT' || id === `ROOT_${treeCfg.dicCfgList[0].nodeInfo}`) {
              if (that.cfg.configInfo.split(',')[0] !== 'JE_COMM_SSQX') {
                that.expandIds = [obj[0].id]; // 默认展开二级
              }
              // loadTree
              // that.loadTree(obj.id)
              console.log(obj);
              // that.loadTree(obj[]);
              that.data = obj;
            }
            // 异步 获取子节点的数据处理 存储到本地store中
            // if (that.async) {
            for (let i = 0; i < obj.length; i++) {
              that.cfg.dataMap[obj[i].id_] = obj[i];
            }
            // }
            if (cfg.callback) {
              cfg.callback(obj);
            }
          }
        },
      });
      console.log(this.data);
    },
    // 异步查询
    doAsyncSearch(keyword) {
      const that = this;
      const dicInfo = this.cfg.treeConfig.dicCfgList[0];

      if (JE.isEmpty(keyword)) {
        // 先重新初始化数据
        this.initConfig();
        this.loadTree('ROOT');
      } else {
        // 查询节点
        JE.ajax({
        // url:'/dd/treeAction!findAsyncNodes.action',
          url: this.cfg.url || JE.getUrlMaps('je.core.dd.tree.findAsyncNodes'),
          params: {
            type: 'liketext',
            value: keyword, // keyword,
            strData: JE.encode([dicInfo]),
          },
          callback(success, obj) {
            that.listsLength = 0;
            that.recursionObj(obj, false);
            that.data = obj;
          },
        });
      }
    },
  },
};
</script>
